//
//  ViewController.m
//  CheckList
//
//  Created by chen on 15/8/3.
//  Copyright (c) 2015年 ZhangXM. All rights reserved.
//

#import "ChecklistViewController.h"
#import "CheckListItem.h"
#import "Checklist.h"

@interface ChecklistViewController ()

@end

@implementation ChecklistViewController{
    NSMutableArray *items;
}

- (NSString *) documentsDirectory{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths firstObject];
    return documentsDirectory;
    
}

- (NSString *)dataFilePath{
    return [[self documentsDirectory] stringByAppendingPathComponent:@"Checklists.plist"];
}

- (void) saveChecklistItem{
    
    NSMutableData *data = [[NSMutableData alloc]init];
    NSKeyedArchiver *archive = [[NSKeyedArchiver alloc]initForWritingWithMutableData:data];
    [archive encodeObject:items forKey:@"CheckListItems"];
    [archive finishEncoding];
    [data writeToFile:[self dataFilePath] atomically:YES];
}

- (void) loadChecklistItem{
    NSString *path = [self dataFilePath];
    if ([[NSFileManager defaultManager]fileExistsAtPath:path]) {
        NSData *data = [[NSData alloc]initWithContentsOfFile:path];
        NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc]initForReadingWithData:data];
        items = [unarchiver decodeObjectForKey:@"CheckListItems"];
        [unarchiver finishDecoding];
    }
    items = [[NSMutableArray alloc]initWithCapacity:20];
}

- (id)initWithCoder:(NSCoder *)aDecoder{
    if ((self = [super initWithCoder:aDecoder])) {
        [self loadChecklistItem];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = self.checklist.name;
    
//    
//    NSLog(@"文件夹目录是：%@",[self documentsDirectory]);
//    NSLog(@"数据文件的最终路劲是：%@",[self dataFilePath]);
//    
//    CheckListItem *item;
//    items = [[NSMutableArray alloc]initWithCapacity:20];
//    
//    // Do any additional setup after loading the view, typically from a nib.
//    item = [[CheckListItem alloc]init];
//    item.text = @"观看嫦娥飞天和玉兔升空视频";
//    item.Checked = NO;
//    [items addObject:item];
//    
//    item = [[CheckListItem alloc]init];
//    item.text = @"了解Sony a7和MBP的最新价格";
//    item.Checked = NO;
//    [items addObject:item];
//    
//    item = [[CheckListItem alloc]init];
//    item.text = @"复习苍老师的经典视频教程";
//    item.Checked = NO;
//    [items addObject:item];
//    
//    item = [[CheckListItem alloc]init];
//    item.text = @"去电影院看地心引力";
//    item.Checked = NO;
//    [items addObject:item];
//
//    item = [[CheckListItem alloc]init];
//    item.text = @"看西甲巴萨新败的比赛回放";
//    item.Checked = NO;
//    [items addObject:item];
//
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return items.count;
}
- (void) configureCheckmarkForCell:(UITableViewCell *)cell withCheckListItem:(CheckListItem *)item{
    UILabel *label = (UILabel *)[cell viewWithTag:1001];
    if (item.Checked) {
        label.text = @"√";
    }else{
        label.text = @"";
    }
    
}
- (void) configureTextForCell:(UITableViewCell *)cell withCheckListItem:(CheckListItem *)item{
   
    UILabel *label = (UILabel *)[cell viewWithTag:1000];
    label.text = item.text;

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CheckListItem"];
    
    CheckListItem *item = items[indexPath.row];
    
    [self configureCheckmarkForCell:cell withCheckListItem:item];
    [self configureTextForCell:cell withCheckListItem:item];
    
    return cell;
}
- (void)tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    
    CheckListItem *item = items[indexPath.row];
    [item toggleChecked];
    
    [self configureCheckmarkForCell:cell withCheckListItem:item];
    [self saveChecklistItem];
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

}

- (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    [items removeObjectAtIndex:indexPath.row];
    [self saveChecklistItem];
    
    NSArray *indexPaths = @[indexPath];
    [self.tableView deleteRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationFade];

}
- (void) addItemViewControllerDidCancel:(AddItemViewController *)controller{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    if ([segue.identifier isEqualToString:@"AddItem"]) {
        UINavigationController *navigationController = segue.destinationViewController;
        AddItemViewController *controller = (AddItemViewController *)navigationController.topViewController;
        controller.delegate = self;
    }else if ([segue.identifier isEqualToString:@"EditItem"]){
        UINavigationController *navigationController = segue.destinationViewController;
        AddItemViewController *controller = (AddItemViewController *)navigationController.topViewController;
        controller.delegate = self;
        
        NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];
        controller.itemToEdit = items[indexPath.row];
    }
}

- (void) addItemViewController:(AddItemViewController *)controller didFinishAddingItem:(CheckListItem *)item{
    
    NSInteger newRowIndex = items.count;
    [items addObject:item];
    
    NSIndexPath *indexpath = [NSIndexPath indexPathForItem:newRowIndex inSection:0];
    NSArray *indexPaths = @[indexpath];
    [self.tableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationAutomatic];
    
    [self saveChecklistItem];
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void) addItemViewController:(AddItemViewController *)controller didFinishEditingItem:(CheckListItem *)item{
    NSInteger index = [items indexOfObject:item];
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:index inSection:0];
    UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    [self configureTextForCell:cell withCheckListItem:item];
    [self saveChecklistItem];
    [self dismissViewControllerAnimated:YES completion:nil];
}

@end
